package storageManager;
import java.util.ArrayList;


public class DataPage extends Page{
	public ArrayList<DataRecord> dataRecords;
	public int numberOfAvailableRecords;
	public DataPage(){
		
	}
	public ArrayList<DataRecord> getDataRecords() {
		return dataRecords;
	}
	public void setDataRecords(ArrayList<DataRecord> dataRecords) {
		this.dataRecords = dataRecords;
	}
	public int getNumberOfAvailableRecords() {
		return numberOfAvailableRecords;
	}
	public void setNumberOfAvailableRecords(int numberOfAvailableRecords) {
		this.numberOfAvailableRecords = numberOfAvailableRecords;
	}
	public int addDataRecord(DataRecord record){//Adds the given data record in the first available place
		int placeToAdd = firstAvailableRecord();
		if(placeToAdd<0){
			this.dataRecords.add(record);//If there is no deleted file it adds the record to the end of the list.
		}else{
			this.dataRecords.set(placeToAdd, record);//If there is a deleted record it replace it with the given record.
		}
		this.numberOfAvailableRecords--;
		return dataRecords.indexOf(record);
	}
	public void deleteARecord(int recordNumber){//Logically delete the record
		dataRecords.get(recordNumber).setStatus(2);
		this.numberOfAvailableRecords++;
	}
	public int firstAvailableRecord(){//This method checks every record and if it finds a deleted record, it returns the index of it, if there is no deleted record it returns -1.
		int size = dataRecords.size();
		for(int i=0;i<size;i++){
			DataRecord record = dataRecords.get(i);
			if(record.getStatus()==0 || record.getStatus()==2){
				return i;
			}
		}
		return -1;
	}
	public DataRecord findDataRecord(int recordNumber){//Returns the data record in the given index of the list
		return dataRecords.get(recordNumber);
	}
	public byte[] toByte(TableRecord tableRecord){//Parse the table object to a byte array.
		byte[] result = new byte[512];
		result[0] =  (byte) numberOfAvailableRecords;
		for(int i=0;i<dataRecords.size();i++){
			DataRecord record = dataRecords.get(i);
			byte[] bytes = record.toByte(tableRecord);
			System.arraycopy(bytes, 0, result, 1+i*tableRecord.getSizeOfADataRecord(),tableRecord.getSizeOfADataRecord());
		}
		return result;
	}
}
